/**
 * 创建人:  @author huangpeng    
 * 创建时间:  2023年01月07日 15:04
 * 项目名称:  lemon-blog-cloud
 * 文件名称:  BiUserServiceImpl
 * 文件描述:  @Description: 普通用户service实现类
 * 公司名称:  柠檬
 *
 * All rights Reserved, Designed By 柠檬 
 * @Copyright: 2022-2023
 *
 */
package com.lemon.blog.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.lemon.blog.web.domain.BiUserFollow;
import com.lemon.blog.web.mapper.*;
import com.lemon.blog.web.vo.ResetPwdVO;
import com.lemon.common.core.constant.Constants;
import com.lemon.common.core.exception.ServiceException;
import com.lemon.common.core.utils.StringUtils;
import com.lemon.common.security.service.BaseServiceImpl;
import com.lemon.blog.web.domain.BiUser;
import com.lemon.blog.web.service.BiUserService;
import com.lemon.common.security.utils.OptEntityUtils;
import com.lemon.common.security.utils.SecurityUtils;
import com.lemon.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名称：com.lemon.blog.web.service.impl
 * 类名称：BiUserServiceImpl
 * 类描述：普通用户service实现类
 * 创建人：@author huangpeng
 * 创建时间：2023年01月07日 15:04
 */
@Service
public class BiUserServiceImpl extends BaseServiceImpl<BiUser> implements BiUserService  {

    @Autowired
    private BiUserMapper userMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BlBlogMapper blBlogMapper;

    @Autowired
    private BlBlogOptionsMapper blogOptionsMapper;

    @Autowired
    private BlCommentMapper commentMapper;

    @Autowired
    private BiUserFollowMapper userFollowMapper;

    @Override
    public List<BiUser> selectBiUserList(BiUser biUser) {
        List<BiUser> biUserList = userMapper.selectBiUserList(biUser);
        for (BiUser model : biUserList) {
            model.setPassword(null);
            model.setUserStatsMap(getUserIllustrate(model.getId()));
        }
        return biUserList;
    }

    @Override
    public int insert(BiUser model) {
        // 判断用户编码是否已存在
        BiUser existUser = userMapper.selectByUserCode(model.getUserCode());
        if (existUser != null) {
            throw new ServiceException("登录名已存在！");
        }
        if (StringUtils.isEmpty(model.getPassword())) {
            throw new ServiceException("密码不能为空！");
        }
        model.setPassword(SecurityUtils.encryptPassword(model.getPassword()));
        OptEntityUtils.preInsert(model);
        return userMapper.insertSelective(model);
    }

    @Override
    public int update(BiUser model) {
        checkAuth(model);
        BiUser currUser = userMapper.selectByPrimaryKey(model.getId());
        if (currUser != null && !currUser.getUserCode().equals(model.getUserCode())) {
            // 判断登录名是否已存在
            BiUser existUser = userMapper.selectByUserCode(model.getUserCode());
            if (existUser != null) {
                throw new ServiceException("当前登录名已存在！");
            }
        }
        model.setPassword(null);
        OptEntityUtils.preUpdate(model);
        return userMapper.updateByPrimaryKeySelective(model);
    }

    @Override
    public List<BiUser> queryBaseUserListByKey(Long[] userIds) {
        return userMapper.queryBaseUserListByKey(userIds);
    }

    @Override
    public BiUser selectByUserCode(String userCode) {
        return userMapper.selectByUserCode(userCode);
    }

    @Override
    public int resetPwd(ResetPwdVO model) {
        // 取消旧密码判断，改用通过邮件验证码校验用户
        BiUser biUser = userMapper.selectByEmail(model.getEmail());
        if (biUser == null) {
            throw new ServiceException("用户不存在");
        }
        BiUser user = new BiUser();
        user.setId(biUser.getId());
        user.setPassword(SecurityUtils.encryptPassword(model.getNewPassword()));
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Map<String, Object> getUserIllustrate(Long userId) {
        Map<String, Object> myOptionsMap;
        Map<String, Object> hasOptionsMap;
        Map<String, Object> resultMap = new HashMap<>(6);
        Map<String, Object> userMap;
        BiUser user = userMapper.selectByPrimaryKey(userId);
        // 获取文章数量
        int blogCount = blBlogMapper.selectBlogCountByUserId(userId, SecurityUtils.getWebUserId());
        // 获取我的评论数量
        Integer commentCount = commentMapper.selectCountByUserId(userId);
        // 获取被点赞、被点踩、被收藏的文章数量
        hasOptionsMap = blBlogMapper.selectHasOptionsCountByUserId(userId);
        // 获取用户的关注数量
        int followCount = userMapper.queryFollowList(new BiUser(userId, null)).size();
        // 获取用户的被关注数量
        int followMeCount = userMapper.queryFollowList(new BiUser(null, userId)).size();
        if (user == null) {
            SysUser sysUser = sysUserMapper.selectByAdminId(userId);
            if (sysUser != null) {
                sysUser.setUserName(sysUser.getNickName());
                userMap = BeanUtil.beanToMap(sysUser);
                resultMap.putAll(userMap);
            }
        } else {
            userMap = BeanUtil.beanToMap(user);
            // 获取我的阅读、点赞、点踩和收藏数量；管理员没有我的阅读、点赞、点踩和收藏
            myOptionsMap = blogOptionsMapper.selectMyOptionsCountByUserId(userId);
            resultMap.putAll(userMap);
            if(myOptionsMap != null) {
                resultMap.putAll(myOptionsMap);
            }
        }
        resultMap.put("userId", userId);
        resultMap.put("blogCount", blogCount);
        resultMap.put("commentCount", commentCount);
        resultMap.put("dvFollow", getDvFollow(userId));
        resultMap.put("followCount", followCount);
        resultMap.put("followMeCount", followMeCount);
        if (hasOptionsMap != null) {
            resultMap.putAll(hasOptionsMap);
        }
        return resultMap;
    }

    @Override
    public List<BiUser> queryFollowList(BiUser biUser) {
        List<BiUser> biUserList = userMapper.queryFollowList(biUser);
        for (BiUser model : biUserList) {
            model.setUserStatsMap(getUserIllustrate(model.getId()));
        }
        Collections.sort(biUserList);
        return biUserList;
    }

    @Override
    public int newUserResetPassword(ResetPwdVO model) {
        BiUser biUser = userMapper.selectByPrimaryKey(SecurityUtils.getWebUserId());
        if (biUser == null || !Constants.STR_FOUR.equals(biUser.getStatus())) {
            throw new ServiceException("当前用户不符合新用户修改密码条件，请使用邮箱验证修改密码");
        } else {
            BiUser user = new BiUser();
            user.setId(biUser.getId());
            user.setPassword(SecurityUtils.encryptPassword(model.getNewPassword()));
            user.setStatus(Constants.STR_ZERO);
            return userMapper.updateByPrimaryKeySelective(user);
        }
    }

    /**
     * 判断是否有修改用户信息的权限
     * @Title: checkAuth
     * @Description: 判断是否有修改用户信息的权限
     * @param biUser
     * @return: void
     * @throws:
     * @author: huangpeng
     * @Date: 2023/9/13 19:42
     */
    private void checkAuth(BiUser biUser) {
        Long currUserId = SecurityUtils.getWebUserId();
        if (!biUser.getId().equals(currUserId)) {
            throw new ServiceException("无权限操作当前数据！");
        }
    }

    /**
     * 获取登录用户是否关注当前查询的用户
     * @Title: getDvFollow
     * @Description: 获取登录用户是否关注当前查询的用户
     * @param followUserId 被关注的用户id
     * @return: int
     * @throws:
     * @author: huangpeng
     * @Date: 2023/10/10 15:37
     */
    private int getDvFollow(Long followUserId) {
        BiUserFollow userFollow = new BiUserFollow();
        userFollow.setUserId(SecurityUtils.getWebUserId());
        if (userFollow.getUserId() == null) {
            return 0;
        } else {
            userFollow.setFollowUserId(followUserId);
            List<BiUserFollow> userFollowList = userFollowMapper.selectBiUserFollowList(userFollow);
            return CollUtil.isNotEmpty(userFollowList) ? 1 : 0;
        }
    }
}
